package com.soul.soulservice.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soul.soulcommon.detail.OlderDetail;
import com.soul.soulcommon.dto.Jwt;
import com.soul.soulcommon.dto.LoginRequest;
import com.soul.soulcommon.dto.RegisterRequest;
import com.soul.soulcommon.result.Result;
import com.soul.soulcommon.utils.JwtUtils;
import com.soul.souldao.domain.Older;
import com.soul.souldao.mapper.OlderMapper;
import com.soul.soulservice.service.OlderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class OlderServiceImp extends ServiceImpl<OlderMapper, Older> implements OlderService {
    @Qualifier("olderAuthenticationManager")
    @Autowired
    private AuthenticationManager olderAuthenticationManager;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private OlderMapper olderMapper;
    /**
     * 登录后返回一个token
     * */
    @Override
    public String login(LoginRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(request.getUserName(), request.getPassword());
        Authentication authenticate = olderAuthenticationManager.authenticate(authenticationToken);
        OlderDetail olderUserDetail = (OlderDetail)  authenticate.getPrincipal();
        String principal = "用户名" + olderUserDetail.getJwt().getUserName() + "登录成功";
        log.info(principal);
        Jwt older = olderUserDetail.getJwt();
        return jwtUtils.generateToken(older.getId(), older.getUserName(), older.getRoleName());
    }
    @Override
    public Result<String> register(RegisterRequest registerRequest){
        //查询数据库中是否有这个用户了
        Older dataOlder = olderMapper.selectOne(new LambdaQueryWrapper<Older>().eq(Older::getUserName, registerRequest.getUserName()));
        if(dataOlder != null){
            return Result.error("用户名已存在");
        }
        //没有存在，可以注册
        Older older = new Older();
        older.setUserName(registerRequest.getUserName());
        older.setPassword(registerRequest.getPassword());
        older.setRoleName(registerRequest.getRoleName());
        older.setEmail(registerRequest.getEmail());
        if(olderMapper.save(older)) {
            return Result.success("注册成功");
        }
        return Result.error("注册失败请联系工作人员");
    }
}

